import jwt
from django.conf import settings
from rest_framework.response import Response
from myapp.models import User
# 登入的校验函数 （高阶函数）

def check_login(func):
    def wrapper(self, request , *args , **kwargs):
        # 从请求头获取token
        token = request.headers.get('Authorization')
        print('封装的',token)
        # 2.解码token,获取用户的信息                待优化
        try:
            payload = jwt.decode(token, key=settings.SECRET_KEY, algorithms=['HS256'])
        except Exception as e:
            print('解码token错误:', e.args)
            return Response({
                'code': 401,
                'msg': '未认证'
            })
        # 3.获取用户的信息,并添加收藏
        print('解码数据', payload)

        request.uid = payload.get('user_id')

        request.user = User.objects.filter(id=request.uid).first()

        # 4.执行真正的添加收藏的函数
        return func(self,request,*args,**kwargs)
    return wrapper









